package cn.bupt.edu.xianyu.controller;

import cn.bupt.edu.xianyu.dao.CommentRepository;
import cn.bupt.edu.xianyu.dao.UserInfoRepository;
import cn.bupt.edu.xianyu.dao.UserRepository;
import cn.bupt.edu.xianyu.dao.XianyuRepository;
import cn.bupt.edu.xianyu.entity.Comment;
import cn.bupt.edu.xianyu.entity.User;
import cn.bupt.edu.xianyu.entity.UserInfo;
import cn.bupt.edu.xianyu.entity.Xianyu;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class IndexController {
    private UserRepository userRepository;
    private XianyuRepository xianyuRepository;
    private CommentRepository commentRepository;
    private UserInfoRepository userInfoRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository){
        this.userRepository = userRepository;
    }
    @Autowired
    public void setXianyuRepository(XianyuRepository xianyuRepository){
        this.xianyuRepository = xianyuRepository;
    }
    @Autowired
    public void setCommentRepository(CommentRepository commentRepository){
        this.commentRepository = commentRepository;
    }
    @Autowired
    public void setUserInfoRepository(UserInfoRepository userInfoRepository){
        this.userInfoRepository = userInfoRepository;
    }
    @RequestMapping("/addXianyu")
    @ResponseBody
    public String addXianyu(@RequestParam("content") String content,
                            HttpServletRequest request) throws IOException {
        String username = (String) request.getSession().getAttribute("username");
        User user = userRepository.findByUsername(username);
        Xianyu xianyu = new Xianyu();
        xianyu.setUsername(username);
        xianyu.setUserId(user.getId());
        Date date = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        xianyu.setDate(date);
        xianyu.setDateString(ft.format(date));
        xianyu.setContent(content);
        xianyu.setLikeNum(0);
        xianyu.setCommentNum(0);
        if(request.getSession().getAttribute("url")!=null){
            xianyu.setUrl((String)request.getSession().getAttribute("url"));
            request.getSession().removeAttribute("url");
        }
        if(request.getSession().getAttribute("lei")!=null){
            xianyu.setLei((int)request.getSession().getAttribute("lei"));
            request.getSession().removeAttribute("lei");
        }
        xianyuRepository.save(xianyu);
        return "success";
    }
    @PostMapping("/addpic")
    @ResponseBody
    public void addPic(@RequestParam String file,
                       HttpServletRequest request) throws IOException {
        String url = file;
        request.getSession().setAttribute("url", url);
    }
    @PostMapping("/addlei")
    @ResponseBody
    public void addType(@RequestParam int lei,HttpServletRequest request){
//        String type = lei;
        request.getSession().setAttribute("lei", lei);
    }

    @GetMapping({"","/index"})
    public String index(HttpServletRequest request, Model model, @RequestParam(value = "type", defaultValue = "1") String type,
                        @RequestParam(value = "start", defaultValue = "0") Integer start,
                        @RequestParam(value = "limit", defaultValue = "3") Integer limit){

        HttpSession session=request.getSession();
        String isLogin=(String)session.getAttribute("isLogin");
        String username=(String)session.getAttribute("username");
        model.addAttribute("isLogin",isLogin);
        model.addAttribute("username",username);
        System.out.println("456");
        start = start < 0 ? 0 : start;
        if(type.equals("1")){
            model.addAttribute("type", "1");
            Sort sort = Sort.by(Sort.Direction.DESC, "date");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        } else if(type.equals("2")){
            model.addAttribute("type", "2");
            Sort sort = Sort.by(Sort.Direction.DESC, "likeNum");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        } else if(type.equals("3")){
            model.addAttribute("type", "3");
            Sort sort = Sort.by(Sort.Direction.DESC, "commentNum");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }else if(type.equals("4")){
            model.addAttribute("type", "4");
            Sort sort = Sort.by(Sort.Direction.ASC, "lei");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }else if(type.equals("5")){
            model.addAttribute("type", "5");
            Sort sort = Sort.by(Sort.Direction.DESC, "lei");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }
        System.out.println("123");
        return "index";
    }
    @PostMapping({"","/index"})
    public String index1(HttpServletRequest request, Model model, @RequestParam(value = "type",defaultValue = "1") String type,
                        @RequestParam(value = "start", defaultValue = "0") Integer start,
                        @RequestParam(value = "limit", defaultValue = "3") Integer limit){
        HttpSession session=request.getSession();
        String isLogin=(String)session.getAttribute("isLogin");
        String username=(String)session.getAttribute("username");
        model.addAttribute("isLogin",isLogin);
        model.addAttribute("username",username);
        System.out.println("456");
        start = start < 0 ? 0 : start;
        if(type == null||type.equals("1")){
            System.out.println("1");
            model.addAttribute("type", "1");
            Sort sort = Sort.by(Sort.Direction.DESC, "date");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        } else if(type.equals("2")){
            model.addAttribute("type", "2");
            Sort sort = Sort.by(Sort.Direction.DESC, "likeNum");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        } else if(type.equals("3")){
            model.addAttribute("type", "3");
            Sort sort = Sort.by(Sort.Direction.DESC, "commentNum");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }else if(type.equals("4")){
            model.addAttribute("type", "4");
            Sort sort = Sort.by(Sort.Direction.ASC, "lei");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }else if(type.equals("5")){
            model.addAttribute("type", "5");
            Sort sort = Sort.by(Sort.Direction.DESC, "lei");
            Pageable pageable = PageRequest.of(start, limit, sort);
            Page<Xianyu> xianyus = xianyuRepository.findAll(pageable);
            model.addAttribute("xianyus", xianyus);
        }
        return "index::xianyuList";
    }
//    @GetMapping("chaxun")
//    public  String cha(@RequestParam String productName){
//
//
//    }

    @RequestMapping("/addComment")
    @ResponseBody
    public String addComment(@RequestParam("content") String content, @RequestParam("id") Long xianyuId,
                             HttpServletRequest request){
        String username = (String) request.getSession().getAttribute("username");
        Comment comment = new Comment();
        comment.setContent(content);
        Date date = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        comment.setDate(date);
        comment.setDataString(ft.format(date));
        comment.setUsername(username);
        comment.setXianyuId(xianyuId);
        commentRepository.save(comment);

        System.out.println("add");
        Xianyu xianyu = xianyuRepository.findById(xianyuId).orElse(null);
        if(xianyu != null){
            xianyu.getComments().add(comment);
            xianyu.setCommentNum(xianyu.getCommentNum()+1);
            xianyuRepository.save(xianyu);
        }
        return "success";
    }
    @RequestMapping("/getComment")
    public String showComments(@RequestParam("id") Long xianyuId, Model model){
        System.out.println("789");
        List<Comment> comments = commentRepository.findByXianyuId(xianyuId);
        if(!comments.isEmpty()){
            System.out.println(comments);
            model.addAttribute("comments",comments);
            System.out.println("123456");
        }
        return "redirect:/index";
    }
    @RequestMapping("/deleteXianyu")
    @ResponseBody
    public String deleteXianyu(@RequestParam int id){
        xianyuRepository.deleteById((long) id);
        return "success";
    }
    @RequestMapping("/like")
    @ResponseBody
    public String like(@RequestParam("xianyuId") Long xianyuId, HttpServletRequest request){
        Xianyu xianyu = xianyuRepository.findById(xianyuId).orElse(null);
        HttpSession session=request.getSession();
        String username=(String)session.getAttribute("username");
        boolean isFind = false;
        if(xianyu != null){
            for(int i = 0; i<xianyu.getLikeUser().size();i++){
                if (xianyu.getLikeUser().get(i).getUsername().equals(username)) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind){
                UserInfo info = userInfoRepository.findByUsername(username);
                xianyu.getLikeUser().add(info);
                xianyu.setLikeNum(xianyu.getLikeNum()+1);
                xianyuRepository.save(xianyu);
            } else {
                UserInfo info = userInfoRepository.findByUsername(username);
                xianyu.getLikeUser().remove(info);
                xianyu.setLikeNum(xianyu.getLikeNum()-1);
                xianyuRepository.save(xianyu);
            }
        }
        return "success";
    }
    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("isLogin");
        request.getSession().removeAttribute("username");

        return "success";
    }

}
